package com.zone.vehicle.superapp.view.login.message;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.zone.sdk.common.http.base.Result;
import com.zone.sdk.module.account.entity.CaptchaGetEntity;
import com.zone.sdk.module.account.entity.CheckCaptchaEntity;
import com.zone.sdk.module.account.entity.LoginEntity;
import com.zone.sdk.module.account.entity.UserInfoEntity;
import com.zone.vehicle.lib.view.captcha.model.CaptchaGetIt;
import com.zone.vehicle.lib.view.captcha.widget.BlockPuzzleDialog;
import com.zone.vehicle.lib.view.captcha.widget.DragImageView;
import com.zone.vehicle.superapp.R;
import com.zone.vehicle.superapp.databinding.FragmentLoginMessageBinding;
import com.zone.vehicle.superapp.model.LoginViewModel;
import com.zone.vehicle.superapp.model.ViewModelFactory;
import com.zone.vehicle.superapp.utils.PhoneUtils;
import com.zone.vehicle.superapp.view.common.base.BaseFragment;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Timer;
import java.util.TimerTask;

import static com.zone.vehicle.superapp.view.login.LoginFragment.FIRST_SET_SECRET_FRAGMENT;
import static com.zone.vehicle.superapp.view.login.LoginFragment.LOGIN_SECRET_FRAGMENT;

public class LoginMessageFragment extends BaseFragment {

    private static final String TAG = LoginMessageFragment.class.getSimpleName();

    private LoginViewModel viewModel;
    private FragmentLoginMessageBinding binding;

    private BlockPuzzleDialog blockPuzzleDialog;
    private Activity activity;

    int time = 60;
    Timer timer = null;
    TimerTask task = null;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        activity = requireActivity();
        binding = FragmentLoginMessageBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        viewModel = new ViewModelProvider(this, new ViewModelFactory())
                .get(LoginViewModel.class);
        initView();
        initListener();
    }
    
    private void initView(){
        blockPuzzleDialog = new BlockPuzzleDialog(this.requireContext());
    }

    private void startTimer(){
        time = 60;
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (time < 1){
                            if (timer != null) {
                                timer.cancel();
                            }
                            binding.btnCode.setTextColor(getResources().getColor(R.color.main_color));
                            binding.btnCode.setClickable(true);
                            binding.btnCode.setText("获取验证码");
                        }else {
                            binding.btnCode.setText(time + "秒后重发");
                            time--;
                        }
                    }
                });
            }
        };
        timer.schedule(task, 0, 1000);
    }

    private void initListener(){

        binding.btnCode.setOnClickListener(v -> {
            if (checkPhone(binding.phone.getText().toString())){
                binding.btnCode.setClickable(false);
                binding.btnCode.setTextColor(Color.GRAY);
                binding.loading.setVisibility(View.VISIBLE);
                viewModel.captchaGet();
                viewModel.getPhone().setValue(binding.phone.getText().toString());
            }
        });

        blockPuzzleDialog.setDragListener(new DragImageView.DragListenner() {
            @Override
            public void onDrag(double position) {
                CaptchaGetEntity entity = viewModel.getCaptchaGet().getValue();
                if (ObjectUtils.isNotEmpty(entity)){
                    viewModel.checkCaptcha(position, entity.getToken(), entity.getSecretKey());
                }
            }
        });

        viewModel.getCaptchaGet().observe(getViewLifecycleOwner(), new Observer<CaptchaGetEntity>() {
            @Override
            public void onChanged(CaptchaGetEntity captchaGetEntity) {
                if (ObjectUtils.isNotEmpty(captchaGetEntity)){
                    binding.loading.setVisibility(View.GONE);
                    CaptchaGetIt data = new CaptchaGetIt();
                    data.setJigsawImageBase64(captchaGetEntity.getJigsawImageBase64());
                    data.setOriginalImageBase64(captchaGetEntity.getOriginalImageBase64());
                    data.setSecretKey(captchaGetEntity.getSecretKey());
                    data.setToken(captchaGetEntity.getToken());
                    blockPuzzleDialog.setData(data);
                    blockPuzzleDialog.show();
                }
            }
        });
        viewModel.getCheckCaptcha().observe(getViewLifecycleOwner(), new Observer<CheckCaptchaEntity>() {
            @Override
            public void onChanged(CheckCaptchaEntity checkCaptchaEntity) {
                if (ObjectUtils.isEmpty(checkCaptchaEntity)){
                    viewModel.captchaGet();
                }
            }
        });
        viewModel.getCaptcha_certificate().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String s) {
                if (StringUtils.isNotEmpty(s)){
                    blockPuzzleDialog.ok();
                    blockPuzzleDialog.cancel();
                    viewModel.loginPhoneCode(requireContext(), binding.phone.getText().toString(), s);
                    startTimer();
                }else {
                    viewModel.captchaGet();
                }
            }
        });

        binding.btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBack();
            }
        });

        binding.secret.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changePage(LOGIN_SECRET_FRAGMENT);
            }
        });

        binding.btnFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = binding.phone.getText().toString();
                String code = binding.code.getText().toString();
                if (checkPhone(phone) && checkCode(code)){
                    viewModel.loginPhoneCodeCheck(getContext(), phone, code);
                }
            }
        });

        viewModel.getUserInfo().observe(getViewLifecycleOwner(), new Observer<UserInfoEntity>() {
            @Override
            public void onChanged(UserInfoEntity userInfoEntity) {
                LoginEntity loginEntity = viewModel.getLoginEntity().getValue();
                if (ObjectUtils.isNotEmpty(loginEntity) && ObjectUtils.isNotEmpty(userInfoEntity)){
                    if (loginEntity.getFirst_login()==2){
                        changePage(FIRST_SET_SECRET_FRAGMENT);
                    }else {
                        // TODO 此处应该判断查询用户信息正确性
                        requireActivity().finish();
                    }
                }

            }
        });

        viewModel.getError().observe(getViewLifecycleOwner(), new Observer<Result>() {
            @Override
            public void onChanged(Result result) {
                if (ObjectUtils.isNotEmpty(result) && StringUtils.isNotEmpty(result.getResultMsg())) {
                    blockPuzzleDialog.fail(result.getResultMsg());
                    showLoginFailed(result.getResultMsg());
                }
            }
        });
    }

    private boolean checkPhone(String phone){
        if (!PhoneUtils.isPhoneNum(phone)){
            Toast.makeText(
                    requireContext(),
                    "请输入手机号码",
                    Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }

    private boolean checkCode(String code){
        if (!StringUtils.isNotEmpty(code)){
            Toast.makeText(
                    requireContext(),
                    "请输入验证码",
                    Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    @Override
    public void finish(){
        requireActivity().finish();
    }

}